#include "circlewidget.h"

#include <QPainter>
#include <QMouseEvent>

#include "circleConstant.h"

CircleWidget::CircleWidget(QWidget *parent) :
	QWidget(parent) {

	ui.setupUi(this);

	cellX = cellY = -1;
	cellWidth = cellHeight = 0;
}

CircleWidget::~CircleWidget() {

}

void CircleWidget::resizeEvent(QResizeEvent * event) {

	cellWidth = width() / cellNum;
	cellHeight = height() / cellNum;
	leftTopX = (width() - cellWidth * cellNum) / 2;
	leftTopY = (height() - cellHeight * cellNum) / 2;
}

void CircleWidget::mouseMoveEvent(QMouseEvent * event) {

	mousePosX = event->x();
	mousePosY = event->y();

	if (cellWidth > 0) {

		int tmpCellX = (mousePosX - leftTopX) / cellWidth;
		if (tmpCellX >= 0 && tmpCellX <= 100) {

			if (cellX == -1 || cellX != tmpCellX) {
				cellX = tmpCellX - cellNum / 2;
				emit cellXChanged(cellX);
			}
		}
	}

	if (cellHeight > 0) {

		int tmpCellY = (mousePosY - leftTopY) / cellHeight;
		if (tmpCellY >= 0 && tmpCellY <= 100) {

			if (cellY == -1 || cellY != tmpCellY) {
				cellY = tmpCellY - cellNum / 2;
				emit cellYChanged(cellY);
			}
		}
	}
}

void CircleWidget::paintEvent(QPaintEvent * event) {

	QPainter painter(this);

	for (int i = 0; i <= cellNum; ++i) {

		painter.drawLine(leftTopX, leftTopY + cellHeight * i, leftTopX
				+ cellWidth * cellNum, leftTopY + cellHeight * i);
		painter.drawLine(leftTopX + cellWidth * i, leftTopY, leftTopX
				+ cellWidth * i, leftTopY + cellHeight * cellNum);
	}

	int r = cellNum / 2;
	int x = 0, y = r;
	painter.fillRect(leftTopX + (r + x) * cellWidth, leftTopY + (r - y)
			* cellHeight, cellWidth, cellHeight, Qt::SolidPattern);

	float d = 1.25 - r;
	while (x <= y) {

		if (d < 0) {
			d += 2 * x + 3;
		} else {
			d += 2 * (x - y) + 5;
			--y;
		}
		++x;
		painter.fillRect(leftTopX + (r + x) * cellWidth, leftTopY + (r - y)
				* cellHeight, cellWidth, cellHeight, Qt::SolidPattern);
		painter.fillRect(leftTopX + (r + y) * cellWidth, leftTopY + (r - x)
				* cellHeight, cellWidth, cellHeight, Qt::SolidPattern);
		painter.fillRect(leftTopX + (r - x) * cellWidth, leftTopY + (r - y)
				* cellHeight, cellWidth, cellHeight, Qt::SolidPattern);
		painter.fillRect(leftTopX + (r + y) * cellWidth, leftTopY + (r + x)
				* cellHeight, cellWidth, cellHeight, Qt::SolidPattern);
		painter.fillRect(leftTopX + (r + x) * cellWidth, leftTopY + (r + y)
				* cellHeight, cellWidth, cellHeight, Qt::SolidPattern);
		painter.fillRect(leftTopX + (r - y) * cellWidth, leftTopY + (r - x)
				* cellHeight, cellWidth, cellHeight, Qt::SolidPattern);
		painter.fillRect(leftTopX + (r - x) * cellWidth, leftTopY + (r + y)
				* cellHeight, cellWidth, cellHeight, Qt::SolidPattern);
		painter.fillRect(leftTopX + (r - y) * cellWidth, leftTopY + (r + x)
				* cellHeight, cellWidth, cellHeight, Qt::SolidPattern);
	}
}
